#!/bin/bash
#
# Runs all test harnesses
#
# Author:   Dr. Mike Murphy (mmurphy2@coastal.edu)
# Revision: 18 November 2013
#
#   Copyright 2013 Coastal Carolina University
#
#   Licensed under the Apache License, Version 2.0 (the "License");
#   you may not use this file except in compliance with the License.
#   You may obtain a copy of the License at
#
#       http://www.apache.org/licenses/LICENSE-2.0
#
#   Unless required by applicable law or agreed to in writing, software
#   distributed under the License is distributed on an "AS IS" BASIS,
#   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
#   See the License for the specific language governing permissions and
#   limitations under the License.
#

starttime=$(date +%s)

if [[ -z "${PULLEY_TEST_TEMP}" ]]; then
	export PULLEY_TEST_TEMP=/tmp/pulley_test
fi

if [[ -z "${PULLEY_ROOT}" ]]; then
	myself=$(readlink -f "$0")
	whereami=$(dirname "${myself}")
	
	# Pulley root should be 1 directory up
	export PULLEY_ROOT=$(dirname "${whereami}")
fi

if [[ -z "${PULLEY_TEST_HOME}" ]]; then
	export PULLEY_TEST_HOME="${PULLEY_ROOT}/tests"
fi

if [[ ! -d "${PULLEY_TEST_TEMP}" ]]; then
	mkdir -p "${PULLEY_TEST_TEMP}" || exit 1
fi

status=0
"${PULLEY_TEST_HOME}/components/check_syntax"
chk=$?

if [[ ${chk} -eq 0 ]]; then
	echo "==> Pulley Syntax OK"
else
	echo "==> Pulley Syntax ERROR"
	status=${chk}
	
	if [[ "${PULLEY_TEST_CONTINUE}" != "true" ]]; then
		echo "==> Aborting"
		exit ${chk}
	else
		echo "==> Continuing"
	fi
fi

for testcase in $(ls "${PULLEY_TEST_HOME}/testcases"); do
	if [[ -x "${PULLEY_TEST_HOME}/testcases/${testcase}" ]]; then
		echo ""
		echo "==> Running Test ${testcase}"
		
		"${PULLEY_TEST_HOME}/testcases/${testcase}"
		chk=$?
		
		if [[ ${chk} -ne 0 ]]; then
			echo "==> Test ${testcase}: FAILED"
			status=${chk}
			
			if [[ "${PULLEY_TEST_CONTINUE}" != "true" ]]; then
				echo "==> Aborting"
				break
			else
				echo "==> Continuing"
			fi
		else
			echo "==> Test ${testcase}: PASSED"
		fi
	fi
done

endtime=$(date +%s)
runtime=$((endtime - starttime))

echo ""
echo "==> Tests complete (status: ${status} time: ${runtime} s)"
echo ""

echo "==> Tree created in: ${PULLEY_TEST_TEMP}"
echo -n "==> Remove it (y/N)? "
read -e answer

if [[ "${answer}" == "y" && "${PULLEY_TEST_TEMP}" != "/" ]]; then
	echo ""
	echo "==> Removing ${PULLEY_TEST_TEMP}"
	rm -rf "${PULLEY_TEST_TEMP}"
else
	echo ""
	echo "==> Preserving ${PULLEY_TEST_TEMP}"
fi

exit ${status}
